#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
CronPy调度器启动脚本
用于系统启动时自动启动调度器
"""

import sys
import os
import time
import signal
import logging

# 添加项目路径
current_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, current_dir)
sys.path.insert(0, os.path.join(current_dir, 'scheduler'))

def signal_handler(signum, frame):
    """信号处理函数"""
    print('\n收到停止信号，正在停止调度器...')
    if 'scheduler' in globals():
        try:
            scheduler.stop()
            print('调度器已停止')
        except:
            pass
    sys.exit(0)

def main():
    """主函数"""
    try:
        # 设置信号处理
        signal.signal(signal.SIGINT, signal_handler)
        signal.signal(signal.SIGTERM, signal_handler)

        print('CronPy调度器正在启动...')

        # 导入必要的模块
        from scheduler.task_scheduler import TaskScheduler
        from scheduler.config_manager import ConfigManager

        # 初始化配置管理器
        config_manager = ConfigManager('../config')

        # 获取配置
        scheduler_config = config_manager.get_scheduler_config()
        max_workers = scheduler_config.get('max_workers', 5)
        log_file = scheduler_config.get('log_file', 'scheduler.log')

        # 设置日志
        logging.basicConfig(
            level=logging.INFO,
            format='%(asctime)s [%(levelname)s] %(message)s',
            handlers=[
                logging.FileHandler(log_file, encoding='utf-8'),
                logging.StreamHandler()
            ]
        )

        # 创建调度器
        global scheduler
        scheduler = TaskScheduler(max_workers=max_workers, log_file=log_file)

        # 加载任务
        tasks = config_manager.load_all_tasks()
        loaded_count = 0
        for task in tasks:
            if task.enabled:
                scheduler.add_task(task)
                loaded_count += 1
                print(f'加载任务: {task.name} ({task.task_id})')

        print(f'调度器启动完成，共加载 {loaded_count} 个任务')
        print('调度器正在运行... 按Ctrl+C停止')

        # 启动调度器
        scheduler.start()

        # 保持运行
        try:
            while True:
                time.sleep(1)
        except KeyboardInterrupt:
            print('\n正在停止调度器...')
            scheduler.stop()
            print('调度器已停止')

    except Exception as e:
        print(f'启动调度器时出错: {e}')
        import traceback
        traceback.print_exc()
        sys.exit(1)

if __name__ == "__main__":
    main()
